package com.bdqn.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    //session工厂
    private static SqlSessionFactory factory;
    static {
        try {
            String resource = "mybatis-config.xml";
            //加载Mybatis框架主配置文件
            InputStream is = Resources.getResourceAsStream(resource);

            //2.创建SqlSessionFactory
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtil.createSession();
        System.out.println(sqlSession);
    }

    //获得session
    public static SqlSession createSession(){

        return factory.openSession(false);//关闭自动提交，开启事务控制
    }

    //关闭session
    public static void closeSqlSession(SqlSession sqlSession){
        if (sqlSession!=null){
            sqlSession.close();
        }
    }
}
